/**
 * Created by sjg on 2017/8/8.
 */

var ItbItemsModel = require('../../../common/mysql/mapping/ItbItemsModel');
var TgUserDocModel = require('../../../common/mysql/mapping/TgUserDocModel');
var ItbActivityModel = require('../../../common/mysql/mapping/ItbActivityModel');
var ItbActivityRModel = require('../../../common/mysql/mapping/ItbActivityRModel');
var ItbTradeOrderModel = require('../../../common/mysql/mapping/ItbTradeOrderModel');
var ItbTradeOrderDetailModel = require('../../../common/mysql/mapping/ItbTradeOrderDetailModel');
var ItbCouponModel = require('../../../common/mysql/mapping/ItbCouponModel');
var ItbQtyPriceModel = require('../../../common/mysql/mapping/ItbQtyPriceModel');

var CommonUtil = require('../../../common/util/CommonUtil');
var CONFIG = require('../../../common/config');

var payUtil = require('../util/payUtil');
var printUtil = require('../util/printUtil');
var luaUtil = require('../util/luaUtil');

var moment = require('moment');  // 日期格式化
var async = require('async');
var superagent = require('superagent');
var nodemailer = require('nodemailer');
var SJGTGV3 = require('./../../sjg/common/tg3/SJGTGV3');

var activityUtil = (function(){

    function activityUtil() {
    }
    //--------------------------------------------------------------------------------------------

    //------------------------------------------------------------------
    // 返回json
    activityUtil.ret_func_json = function (success, msg, data, res){
        var obj = {
            success: success,
            msg: msg,
            data: data
        };
        // 返回
        res.set('Content-Type', 'application/json');
        res.json(obj);
    };

    //------------------------------------------------------------------
    // 获取预结算秒杀商品信息
    activityUtil.getActivityPreOrderInfo_v6_1 = function(userId, actItemId, couponId, callback) {
        // 获取秒杀商品价格
        var entActR = new ItbActivityRModel;
        entActR.findMinQtyPriceByActItemId(actItemId, function(findErr, priceInfo){
            if(findErr) {
                return callback(findErr, null);
            }

            if(priceInfo) {
                // 返回值
                var retData = {
                    totalFee: Number(priceInfo.act_price||'0')||0,
                    itemFee : Number(priceInfo.act_price||'0')||0,// 活动价格
                    actItemInfo: {},
                    couponCnt: 0,
                    couponInfo: {}
                };

                entActR.geActItemInfo(actItemId, function(getErr, actItemInfo){
                    if(getErr) {
                        return callback(getErr, null);
                    }

                    if(actItemInfo) {
                        retData.actItemInfo = actItemInfo;

                        // 获取可用优惠券数
                        (new ItbCouponModel).getSeckillCouponInfoCnt(userId, actItemId, 1/*可用的*/, function (err, cnt) {
                            if(err) {
                                return callback(err, null);
                            }

                            retData.couponCnt = cnt||0;

                            if(Number(couponId||'0')>0) {
                                // 检查指定的优惠券
                                (new ItbCouponModel).getCouponInfoById(couponId, function(chkErr, retCouponInfo){
                                    if(chkErr) {
                                        return callback(chkErr, null);
                                    }

                                    if(retCouponInfo) {
                                        retData.couponInfo = printUtil.genCouponRetInfo(retCouponInfo, userId, 0);
                                        // TODO 仅logo优惠价可用
                                        if(retData.couponInfo.limit_type !=1010 && retData.couponInfo.reason.length==0) {
                                            retData.couponInfo.reason = '不匹配';
                                        }
                                    } else {
                                        retData.couponInfo.reason = '无效优惠券';
                                    }

                                    if(retData.couponInfo.reason.length==0) {
                                        // 扣除优惠金额
                                        retData.totalFee = retData.totalFee-Number(retCouponInfo.discount||'0');
                                        if(retData.totalFee<0) {
                                            retData.totalFee = 0;
                                        }
                                    }

                                    return callback(null, retData);

                                });

                            } else {
                                return callback(null, retData);
                            }
                        });

                    } else {
                        return callback('未获取到商品信息', null);
                    }
                });

            } else {
                return callback('未获取到价格信息', null);
            }
        });
    };

    //------------------------------------------------------------------
    /**
     * 获取预结算秒杀商品可使用/不可使用优惠券列表
     * @param valid: 0获取不可用优惠券,1获取可用优惠券
     * */
    activityUtil.getSeckillCouponInfo_v6_1 = function(userId, actItemId, valid, pageNum, pageSize, callback) {
        (new ItbCouponModel).getSeckillCouponInfo(userId, actItemId, valid, pageNum, pageSize, function(err, retInfo){
            if(err){
                return callback(err, null);
            }

            if(retInfo && retInfo.length>0) {
                var retData = [];
                for(var i=0; i<retInfo.length; i++) {
                    var info = retInfo[i];
                    var cInfo = printUtil.genCouponRetInfo(info, userId, 0);
                    if(cInfo && cInfo.id){
                        // TODO 秒杀暂定仅能使用logo券
                        if(!valid && cInfo.limit_type != 1010 && !cInfo.reason) {
                            cInfo.reason = "不匹配";
                        }
                        retData.push(cInfo);
                    }
                }
                return callback(null, retData);

            } else {
                return callback(null, []);
            }
        });
    };
    activityUtil.getSeckillCouponInfoCnt_v6_1 = function(userId, actItemId, valid, callback) {
        (new ItbCouponModel).getSeckillCouponInfoCnt(userId, actItemId, valid, function(err, cnt){
            return callback(err, cnt||0);
        });
    };

    //------------------------------------------------------------------
    /**
     * 创建秒杀订单
     * */
    activityUtil.crtSeckillOrder_v6_1 = function(device, userId, actItemId, couponId, callback) {
        // 获取商品价格
        (new ItbActivityRModel).findMinQtyPriceByActItemId(actItemId, function(findErr, priceInfo){
            if(findErr) {
                return callback(findErr, null);
            }

            if(priceInfo) {
                // 创建订单编号
                printUtil.createOrderNo(device, 50/*秒杀订单*/, function(crtErr, orderNo){
                    if(orderNo){
                        // 新建订单
                        var newEntity = new ItbTradeOrderModel({
                            order_no: orderNo,
                            pay_order_no: orderNo,
                            detail_cnt: 1,
                            device: device, // 记录来源
                            state: 10,// 待支付
                            type: 20,// 原始秒杀订单!!!
                            hide: 1,// 订单列表不显示
                            partner_id: 100,// 100:示界港
                            pay_platform: 10,// 10微信, 20支付宝, 30苹果内购
                            total_fee: Number(priceInfo.act_price||'0'),// 活动价格
                            user_id: userId,
                            update_by: userId
                        });
                        // 创建订单
                        newEntity.saveToDB(function(saveErr, newOrderId){
                            if(saveErr){
                                return callback(saveErr, null);
                            }
                            if(!newOrderId){
                                return callback('订单创建失败', null);
                            }

                            // 创建子订单
                            var newEntity2 = new ItbTradeOrderDetailModel({
                                detail_no: '0',// 秒杀支付订单 子订单号：暂定为0
                                order_id: newOrderId,
                                item_id: actItemId,// 秒杀项目id
                                pp_id: 0,//priceInfo.pp_id ,
                                unit: '件',// 1件秒杀商品
                                qty: 1,// 1件秒杀商品
                                //user_doc_id: null,
                                fee: Number(priceInfo.act_price||'0'),
                                product_fee: Number(priceInfo.act_price||'0'),// 活动价格
                                design_fee: 0,
                                mail_fee: 0,
                                update_by: userId
                            });

                            // 创建子订单
                            newEntity2.saveToDB(function(saveErr2, newOrderDetailId){
                                if(saveErr2){
                                    return callback(saveErr2, null);
                                }
                                if(!newOrderDetailId){
                                    return callback('子订单创建失败', null);
                                }

                                if(Number(couponId||'0')>0) {
                                    // 检查优惠券
                                    (new ItbCouponModel).getCouponInfoById(couponId, function(chkErr, couponInfo){
                                        if(chkErr) {
                                            return callback(chkErr, null);
                                        }

                                        if(couponInfo) {
                                            // 绑定优惠券
                                            printUtil.bindCouponToTradeOrder_v5_2(userId, newOrderId, couponId, function(bindErr, bindRet){
                                                var useCoupon = (bindErr)?0:1;
                                                return callback(bindErr, {orderId:newOrderId, orderNo:orderNo, useCoupon:useCoupon});
                                            });
                                        } else {
                                            return callback('无效优惠券', null);
                                        }
                                    });

                                } else {
                                    return callback(null, {orderId:newOrderId, orderNo:orderNo, useCoupon:0});
                                }
                            });
                        });

                    }else{
                        return callback('创建订单失败', null);
                    }
                });

            } else {
                return callback('未获取到价格信息', null);
            }
        });
    };

    //------------------------------------------------------------------
    /**
     * 获取用户秒杀列表
     *
     * 参数 userId: 用户唯一标识
     * 参数 state: 暂定: 10, 可用, 20 已用, 30 失效, 40 待支付
     * */
    activityUtil.getUserActivityList_v6_1 = function(userId, state, pageNum, pageSize, callback) {

        (new ItbTradeOrderModel).getUserSeckillActivityList(userId, state, pageNum, pageSize,function(err, ret){
            if(err) {
                return callback(err, null);
            }

            return callback(null, ret);
        });
    };

    //------------------------------------------------------------------
    /**
     * 获取已发布的秒杀场次列表
     * */
    activityUtil.getCurrentActivityList = function(callback) {

        (new ItbActivityModel).getPublishActivitys(function(error, activitys){
            if(error || !activitys || activitys.length == 0) {
                return callback(error, activitys);
            }
            var acts = [];
            for(var i=0; i<activitys.length; i++) {
                acts.push({
                    id : activitys[i].act_id,
                    title : activitys[i].title
                });
            }
            return callback(error, acts);
        });
    };

    /**
     * 获取指定场次的秒杀项目列表及场次信息
     * */
    activityUtil.getActivityAndItems = function(id, pageNum, pageSize, callback) {

        // 1. 获取场次内项目列表
        (new ItbActivityRModel).getActivityItems(id, pageNum, pageSize, function(getItemsErr, items){
            if(getItemsErr) {
                return callback(getItemsErr, null)
            }
            // 解析 thumbs
            for(var i=0; i<items.length; i++) {
                items[i].thumbs = JSON.parse(items[i].thumbs) || [];
                items[i].thumb =  items[i].thumb || items[i].thumbs[0] || "";
            }
            // 2. 获取场次信息
            activityUtil.getActivityBriefInfo(id, function(getActErr, act){
                if(getActErr || !act) {
                    return  callback(getActErr, null);
                }
                act.items = items || [];
                return callback(getActErr, act);
            });
        });
    };
    /**
     * 获取秒杀场次基本信息
     *
     * @param actId 场次唯一标识
     * @param callback
     *            err: 错误
     *            act: {
     *              id : 1,
     *              title : "场次标题",
     *              desc : "场次描述",
     *              startTime : "场次开始时间",
     *              endTime : "场次结束时间",
     *              state :  10 // 10 未开场, 20, 已开场, 30 已结束
     *            }
     *
     * */
    activityUtil.getActivityBriefInfo = function(actId, callback) {
        // 1. 获取指定场次信息
        var entity = new ItbActivityModel({
            act_id : actId,
            del_flg: 0
        });
        entity.findFromDB(function(getActErr, results) {
            if (getActErr) {
                return callback(getActErr, null)
            }
            if (results.length == 0) {
                return callback("无此场次", null);
            }
            var activity = results[0];
            var retJson = {
                id: activity.act_id,
                title: activity.title,
                desc: activity.desc,
                startTime: (new moment(activity.start_time).unix()),
                endTime: (new moment(activity.end_time).unix())
            };
            // 计算状态
            retJson.currentTime = (new moment().unix());
            if(retJson.currentTime < retJson.startTime ) {
                retJson.state = 10;
            }
            else if(retJson.currentTime >= retJson.startTime && retJson.currentTime <= retJson.endTime) {
                retJson.state = 20;
            }
            else if (retJson.currentTime > retJson.endTime) {
                retJson.state = 30;
            }
            return callback(getActErr, retJson);
        });
    };

    /**
     * 获取一个秒杀项目详细信息
     *
     * @param actItemId 秒杀条目详细信息
     * @param callback 回调
     *          err: 错误原因
     *          item : {
     *                  "id" : 1, // 秒杀项目 id
                        "itemId" : 999,
                        "typeL" : 1010,
                        "typeM" : 10100100,
                        "title" : "logo 商品名称",
                        "orgPrice" : 998,
                        "actPrice" : 288,
                        "qty" : 1,
                        "rest_qty" : 1,
                        "thumbs" : ["http://0ss-img.jpg"],
                        "desc" : "商品说明, 如色差小于百分之十不属于残次品"
     *          }
     * */
    activityUtil.getActItemContent = function(actItemId, callback){
        (new  ItbActivityRModel).getOneItemDetailInfo(actItemId, function(err, item){
            if(err) {
                return callback(err, null);
            }
            if(!item) {
                return callback('无此项目信息', null);
            }
            item.thumbs = JSON.parse(item.thumbs) || [];
            item.thumb =  item.thumb || item.thumbs[0] || "";
            return callback(null, item);
        });
    };

    /**
     *  根据秒杀订单 id 获取订单所需填写资料信息
     *
     * @param actOrderId 活动订单唯一标识
     * @param callback 回调
     *          err: 错误
     *          data: {
     *              docId : 998
     *              coreStructure : {},
     *              desc : "说明: 资料将发送至所填写邮箱",
     *              editable : 1
     *          }
     * */
    activityUtil.getActOrderDocInfo_v6_1 = function(actOrderId, callback) {

        (new ItbTradeOrderModel).getActivityDocInfoByActOrderId(actOrderId, function(err, data){
            if(err) {
                return callback(err, null);
            }
            if(!data) {
                return callback('无此文档资料', null);
            }
            // data.order_id = undefined; 暂不删除order_id, 便于其他接口使用
            // 将data中的coreStructure转换为对象
            data.coreStructure = data.coreStructure
                .replace(/\n/g,'\\n').replace(/\t/g,'').replace(/\r/g,'') //.replace(/\\"/g,'\\\\\\"')
                .replace(/[\x00-\x09\x0B-\x1F\x7F-\x9F]/g, "");
            data.coreStructure = JSON.parse(data.coreStructure);
            data.editable = (data.state == 11 && data.expiry == 0) ? 1 : 0;

            // 支付成功, 第一次更改, 需要清空资料树, 否则不清空
            data.clearValue = data.state == 11 ? 1 : 0;

            // logo
            if(data.typeM == 10100100) {
                data.desc = "说明: 秒杀Logo会发送到以下邮箱";
            }
            // 百度百科
            if(data.typeM == 10110100) {
                data.desc = "说明: 请仔细填写下列信息, 将用于创建您的百度百科信息";
            }
            // 百度地图
            if(data.typeM == 10110200) {
                data.desc = "说明: 请仔细填写下列信息, 将用于创建您的百度地图信息";
            }
            // 不可编辑
            if(data.editable == 0) {
                if(data.state != 11 && data.state <20) {
                    data.desc = "订单未支付, 无法使用";
                }
                if(data.state != 11 && data.state >= 20) {
                    data.desc = "资料已提交, 不可再次编辑";
                }
                if(data.state == 11 && data.expiry == 1) {
                    data.desc = "订单已失效, 无法使用";
                }
            }
            if(!data.desc) data.desc = "说明: 请仔细填写下列信息";
            return callback(err, data);
        });
    };

//------------------------------------------------------------------
    /**
     * 根据活动项目 id 获取相似内容
     * @param actItemId 秒杀项目唯一标识
     * @param pageNum 页码
     * @param pageSize 页容量
     * @param callback 回调
     *          err: 错误
     *          items: [{"id" : 790,"thumb" : "http://oss-img.jpg","typeL" : 4,“kind" : 20}] // kind=10 普通项目, kind=20 秒杀项目
     * */
    activityUtil.getSimilarActivityItemsByActItemId = function(actItemId, pageNum, pageSize,callback) {
        pageNum = pageNum || 0;
        pageSize = pageSize || 12;

        (new ItbActivityRModel).getSimilarItems(actItemId, pageNum, pageSize,function(err, items){
            if(err) {
                return callback(err, items);
            }
            for(var i in items) {
                var item = items[i];
                item.thumbs = JSON.parse(item.thumbs) || [];
                item.thumb =  item.thumb || item.thumbs[0] || "";
                item.kind = 20;
            }
            return callback(err, items);
        });
    };



//----------------------------------------------------------------------------
    /**
     * 更新用户秒杀资料
     *
     * @param userId 用户唯一标识
     * @param actOrderId 秒杀订单唯一标识
     * @param info 资料文档树
     * @param callback 回调
     *          err: 错误
     *
     * **/
    activityUtil.updateActivityOrderDocInfo_v6_1 = function(userId, actOrderId, info, callback) {

            // 1. 获取秒杀订单信息
            // 2. 更新秒杀对应的文档内容
            // 3. 更改订单列表中秒杀订单状态
            // 4. 如果是 logo 分类, 则发送邮件

        // 1. 获取信息
        activityUtil.getActOrderDocInfo_v6_1(actOrderId, function(getDocErr, data){
            if(getDocErr) {
                return callback(getDocErr, null);
            }
            // 秒杀的支付订单简称秒杀支付订单, 订单列表中的秒杀订单称为秒杀订单
            var doc_id = data.doc_id; // 秒杀订单对应的资料 id(作品 id)
            var order_id = data.order_id; // 秒杀订单的唯一标识
            var typeM = data.typeM; // 秒杀商品二级分类(logo, 百度百科, 百度地图)
            async.series([
                function(callback) {
                    // 更新资料
                    activityUtil.updateUserDocInfo(doc_id,userId,info,function(error,data){callback(error,data)});
                },
                function(callback) {
                    // 更新订单状态到制作中
                    activityUtil.updateUserOrderState(order_id, userId, 20, function(error,data){callback(error,data)});
                },
                function(callback) {
                    // 按需处理秒杀订单发货流程
                    activityUtil.activityOrderShipment(order_id,userId, typeM, info,function(error,data){callback(error,data)});
                }
            ],function(err,results){
                return callback(err, null);
            });
        })
    };

    /**
     * 更新用户文档内容
     *
     * @param doc_id 用户文档唯一标识
     * @param userId 用户唯一标识
     * @param info 更新内容(提纲树, data)
     * @param callback
     *          err: 错误
     * */
    activityUtil.updateUserDocInfo = function(doc_id, userId, info, callback) {
        // 更新doc
        var updDocEnt = new TgUserDocModel({
            doc_id: doc_id,// Key
            data: info || '',
            update_by : userId
        });
        updDocEnt.updateToDB(function(err){
            return callback(err);
        });
    };

    /**
     * 更新用户订单状态
     *
     * @param orderId 订单唯一标识
     * @param userId 用户唯一标识
     * @param state 状态 '订单状态:10待支付、11已支付、12支付失败、20制作中、30配送中、40完成、50取消',
     * @param callback 回调
     *          err: 错误
     *
     * */
    activityUtil.updateUserOrderState = function(orderId, userId, state, callback) {
        var orderEntity = new ItbTradeOrderModel({
            order_id  : orderId,
            state : state,
            update_by : userId
        });
        orderEntity.updateToDB(callback);
    };

    /**
     * 秒杀订单发货
     *
     * @param orderId 秒杀订单唯一标识(订单列表中的订单)
     * @param userId 用户唯一标识
     * @param typeM 二级分类(主要用于区分是否为 logo, 若是 logo 则自动发货)
     * @param info 用户填写的资料信息
     * @param callback 回调
     *          err 错误
     *
     * */
    activityUtil.activityOrderShipment = function(orderId, userId, typeM, info,callback) {

        if(typeM != 10100100) {
            return callback(null);
        }

        // 提取邮箱
        var tree = new SJGTGV3();
        tree.fromJson(JSON.parse(info),3);
        if(!tree || !tree.root || !tree.root.children || tree.root.children.length == 0) {
            return callback('未找到接收邮箱');
        }
        var email = null;
        for(var i in tree.root.children) {
            var node = tree.root.children[i];
            if(node.topic && node.topic.indexOf("邮箱") != -1) {
                email = node.value.value;
                break;
            }
        }
        if(!email || email.length == 0) {
            return callback('未找到接收邮箱');
        }

        // 1.查询 logo 源文件
        (new ItbTradeOrderModel).getSeckillActivityOrderSourceUrl(orderId,function(getSrcUrlErr, designDoc){
            if(getSrcUrlErr) {
                return callback(getSrcUrlErr);
            }
            if(!designDoc) {
                return callback('未找到商品');
            }
            // 2. 发送源文件邮件
            var html = "<!DOCTYPE html><html><head><meta charset=\"{CHARSET}\"><title>一键生成</title><style type=\"text/css\">body,html{margin: 0;padding: 0;box-sizing: border-box;padding: 100px;font-size: 16px;}.title{margin-bottom: 10px;text-align: left;}.content{text-indent: 40px;}.content .email{text-indent: 80px;}.foot{margin-top: 10px;text-align: right;}</style></head><body><div class=\"main\"><div class=\"title\">您好</div><div class=\"content\"><p>您在“一键生成”成功秒杀一个Logo，源文件下载地址如下：</p><p class=\"email\">" + designDoc.src_url + "</p><p>如有疑问请联系客服027-87101355。</p><p>此邮件由系统自动发送，请勿回复。</p><p>谢谢！</p></div><div class=\"foot\">一键生成</div></div></body></html>";
            var subject = "一键生成秒杀订单发货";
            activityUtil.sendMail(email,subject,null,html,function(sendEmailErr, res){
                if(sendEmailErr) {
                    return callback(getSrcUrlErr);
                }
                // 3. 更新订单状态
                activityUtil.updateUserOrderState(orderId,userId,40, callback);
            });
        });
    };


    //------------------------------------------------------------------
    /* 发邮件
     *
     * @param toEmails 收件人地址（多个时以逗号分隔: 'xiaochi@itbour.com,liumin@itbour.com'）
     * @param subject 主题
     * @param text 明文内容
     * @param html 附带内容 如: <b>下载地址</b><b>http://itbour-generate.oss-cn-hangzhou.aliyuncs.com/image/U401486/2017/08/07/113922787_iJfiolOa2zVkauuuapfo/0.jpg</b>
     * @param callback 回调
     *          err: 错误
     *          response: 成功响应内容
     * */
    activityUtil.sendMail = function(toEmails, subject, text, html, callback) {
        if (!toEmails || toEmails.length < 1) {
           return callback('收件人邮箱为空');
        }
        var transporter = nodemailer.createTransport({
            host: 'smtpdm.aliyun.com',
            secureConnection: true,// use SSL
            port: 465,// port for secure SMTP
            auth: {
                user: 'send@automail.itbour.com',
                pass: 'xiqihErRoirh87399'
            }
        });
        var mailOptions = {
            from: '"自动发送，请勿回复"<send@automail.itbour.com>', // sender address
            to: toEmails, // list of receivers
            subject: subject, // Subject line
            text: text, // plaintext body
            html: html // html body
        };
        transporter.sendMail(mailOptions, function(error, info){
            if(error){
                console.log('/utils/activityUtil.js [sendMail] sendMail err: ' + error);
                return callback(error)
            }
            return callback(null, info.response);
        });
    };


//--------------------------------------------------------------------------------------------
    return activityUtil;
})();
module.exports = activityUtil;